import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { loginUser } from '../../actions/authActions'
import TextFieldGroup from '../../common/TextFieldGroup';





export class Login extends Component {
  state = {
    email: '',
    password: '',
    errors: ''
  }
  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value })
  }
  onSubmit = (e) => {
    e.preventDefault()
    const newUser = {
      email: this.state.email,
      password: this.state.password,
    }
    this.props.loginUser(newUser)
  }
  // 页面渲染
  componentDidMount () {
    // 如果授权就进入控制面板页面
    if (this.props.auth.isAuthenticated) {
      this.props.history.push('/dashboard')
    }
  }
  // 接受新的数据如果有错误提示就赋值
  UNSAFE_componentWillReceiveProps (nextProps) {
    //判断是否授权
    if (nextProps.auth.isAuthenticated) {
      this.props.history.push('/dashboard')
    } else {
      console.log('没登录');
    }
    if (nextProps.errors) {
      this.setState({ errors: nextProps.errors })
    }
  }
  render () {
    const { errors } = this.props
    return (
      <div className="login ">
        <div className="container">
          <div className="row">
            <div className="col-md-8 m-auto">
              <h1 className="display-4 text-center">登录</h1>
              <p className="lead text-center">使用已有的账户登录</p>
              <form onSubmit={this.onSubmit}>
                <TextFieldGroup
                  type="email"
                  placeholder="邮箱地址"
                  name="email"
                  value={this.state.email}
                  onChange={this.onChange}
                  error={errors.email}
                />

                <TextFieldGroup
                  type="password"
                  placeholder="密码"
                  name="password"
                  value={this.state.password}
                  onChange={this.onChange}
                  error={errors.password}
                />
                <input type="submit" className="btn btn-info btn-block mt-4" />
              </form>
            </div>
          </div>
        </div>
      </div>
    )
  }
}
// 获取reduce中在actions定义的initalStaten属性值
const mapStateToProps = (state) => ({
  errors: state.errors,
  auth: state.auth,
})
// dispatch 方法
const mapDispatchToProps = (dispatch) => {
  return {
    loginUser: (params) => {
      dispatch(loginUser(params))
    }
  }
}
// 定义reduce传过来的类型
Login.propTypes = {
  errors: PropTypes.object.isRequired,
}
export default connect(mapStateToProps, mapDispatchToProps)(Login)


